$(function () {
    var servers = [];
    var show_servers = [];
    var isAdd = false;
    var appendData = function (data) {
        let connect_names = '';
        data.connect_ids.map(function (id) {
            let server = servers.find(function (i) { return i.id == id })
            if (!!server)
                connect_names += server.name + '、'
        })
        connect_names = connect_names.length > 0 ?
            connect_names.substring(0, connect_names.length - 1) :
            '无';
        var ips = data.ips.length > 0 ? data.ips.join(',') : '无';
        var div = `<div>
            <span>${data.name}</span>
            <span>${ips}</span>
            <span>${connect_names}</span>
            <span>
                <button class="edit" data-id="${data.id}">修改</button>
                <button class="del" data-id="${data.id}">删除</button>
            </span>
        </div>`;
        $('.servers main').append($(div))
    }
    var editData = function (data, index) {
        let connect_names = '';
        !!data.connect_ids && data.connect_ids.map(function (id) {
            let server = servers.find(function (i) { return i.id == id })
            if (!!server)
                connect_names += server.name + '、'
        })
        connect_names = connect_names.length > 0 ?
            connect_names.substring(0, connect_names.length - 1) :
            '无';
        var ips = data.ips.length > 0 ? data.ips.join(',') : '无';
        var div = `<div>
            <span>${data.name}</span>
            <span>${ips}</span>
            <span>${connect_names}</span>
            <span>
                <button class="edit" data-id="${data.id}">修改</button>
                <button class="del" data-id="${data.id}">删除</button>
            </span>
        </div>`;
        $('.servers main').children()[index].remove()
        if (index != 0)
            $($('.servers main').children()[index - 1]).after($(div))
        else
            $('.servers main').prepend($(div))
    }
    var create_page = function(data){
        let length = data.length;
        let pages = Math.ceil(length / 5);
        for(let i = pages;i > 0; i--){
            $('.counts').prepend(`<div class="count ${i == 1 ? 'active' : ''}">${i}</div>`)
        }
    }
    $.get('//120.55.85.1:8069/proxy_id{B0884528-25CE-4384-8D72-2B81C9707F2E}/intu/server_list',
        function (data) {
            if (data.length == 0) return;
            else {
                servers = data;
                if (data.length <= 5)
                    data.map(function (item) {
                        appendData(item)
                    })
                else {
                    show_servers = data.slice(0, 5);
                    show_servers.map(function (item) {
                        appendData(item)
                    })
                }
                create_page(servers)
            }
        })
    $('.counts').on('click', '.count', function(){
        $(this).addClass('active').siblings().removeClass('active')
        let count = $(this).html();
        count = parseInt(count);
        // debugger
        show_servers = servers.slice(5 * (count -1), 5 * count);
        $('.servers main').empty();
        show_servers.map(function (item) {
            appendData(item)
        })
    })
    $('.add').on('click', function () {
        isAdd = true;
        $('.data_box').removeClass('nagtive');
        $('#connect_ids').select2({
            data: servers.map(function (item) {
                return { id: item.id, text: item.name }
            }),
            placeholder: '请选择关联服务器',
            allowClear: true
        })
    })
    $('.servers').on('click', '.del', function () {
        var id = $(this).data('id');
        alertMs('确认删除？', 2, function () {
            $.get('//120.55.85.1:8069/proxy_id{B0884528-25CE-4384-8D72-2B81C9707F2E}/intu/del_server?id=' + id, function (data) {
                if (data.errcode != 0) return alertMs(data.errmsg)
                var index = servers.findIndex(function (item) { return item.id == id });
                $($('.servers main').children()[index]).remove()
            })
        })
    })
    $('.servers').on('click', '.edit', function () {
        isAdd = false;
        $('.data_box').removeClass('nagtive');
        var id = $(this).data('id');
        var server = servers.find(function (item) {
            return item.id == id
        });
        var _servers = servers.filter(function (item) { return item.id != id })
        $('#connect_ids').select2({
            data: _servers.map(function (item) {
                return { id: item.id, text: item.name }
            }),
            placeholder: '请选择关联服务器',
            allowClear: true
        })

        $('.input').map(function () {
            var keyInput = $(this).find('input, select');
            keyInput.val(server[keyInput.attr('name')]);
        })
        $('#connect_ids').select2()
    })
    $('.confirm').on('click', function () {
        var server = {};
        $('.input').map(function () {
            var keyInput = $(this).find('input, select');
            server[keyInput.attr('name')] = keyInput.val();
        })
        server.ips = server.ips.replace(/，/g, ',').split(',');
        console.log(server);
        // return ;
        var url = isAdd ? '//120.55.85.1:8069/proxy_id{B0884528-25CE-4384-8D72-2B81C9707F2E}/intu/add_server' :
            '//120.55.85.1:8069/proxy_id{B0884528-25CE-4384-8D72-2B81C9707F2E}/intu/edit_server';
        $.ajax({
            url,
            type: 'POST',
            data: JSON.stringify(server),
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (data) {
                if (data.errcode != 0) alertMs(data.errmsg)
                var index = servers.findIndex(function (item) { return server.id == item.id })
                if (isAdd) {
                    server = data.server;
                    servers.push(server)
                    appendData(server)
                }
                else
                    editData(server, index)
            }
        })
        $('.data_box').addClass('nagtive')
    })
    $('.cancel').on('click', function () {
        $('.input').map(function () {
            var keyInput = $(this).find('input, select');
            keyInput.val('')
        })
        $('.data_box').addClass('nagtive');
    })
})